<?php
/**
 * Created by PhpStorm.
 * User: Administrator--Reer
 * Date: 2019/9/9 0009
 * Time: 13:41
 */

namespace app\common\utils;


class CommonUtil extends BaseUtil
{
    static $_self = null;
    public static function getInstance(){
        if(empty(self::$_self)){
            self::$_self = new CommonUtil();
        }
        return self::$_self;
    }

    public function backData(){
        if($_SERVER['SERVER_ADDR']=='127.0.0.1'){
            return $_POST;
        }else{
            $data = file_get_contents('php://input');
            libxml_disable_entity_loader(true);
            $xml = simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);
            $json_data = json_encode( $xml );
            $data = json_decode($json_data, true);
            $data['out_trade_no'] = substr($data['out_trade_no'], 0, -4);
            return $data;
        }
    }
    /**
     * 支付签名
     * 梁树兴 2018-09-20
     * @param $data array 支付必须参数
     * @param $attach str 附加参数
     * @return $jsApiParameters str 微信支付
     */
    public function weixinPay($data, $attach=''){
        header("Content-Type: text/html; charset=UTF-8");
        \think\Loader::addNamespace([
            'wx'=>'../application/extend/wpay/lib/',
            'example'=>'../application/extend/wpay/example/',
        ]);
        $out_trade_no = proOrder($data['out_trade_no'], 4);
        $total_fee = $data['openid']!='ooWWa5fMZzRwlkxicDT9jWaEUWHY' ? $data['total_fee']*100 : 1;
        $tools = new \example\JsApiPay();
        $wxPayApi = new \wx\WxPayApi();
        $input = new \WxPayUnifiedOrder();
        $input->SetBody( $data['body'] );
        $input->SetAttach($attach);
        $input->SetOut_trade_no( $out_trade_no );
        $input->SetTotal_fee($total_fee);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag( $data['tag'] );
        $input->SetNotify_url( $data['notify_url'] );
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($data['openid']);
        $order = $wxPayApi::unifiedOrder($input);
        $jsApiParameters = $tools->GetJsApiParameters($order);
        return json_decode($jsApiParameters,true);
    }
    /** 获取唯一订单号
     * @param string $fix
     * @param int $count
     * @return string
     */
    public function getUnique($fix = "",$count = 5){
        $orderNumber = $fix.date("YmdHis");
        for($i = 0;$i < $count;$i++){
            $orderNumber .= rand(0,9);
        }
        return $orderNumber;
    }

    /** 获取客户ip
     * @return mixed
     */
    public function getCentIp() {
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            $ipaddress = $_SERVER['REMOTE_ADDR'];
        }
        return $ipaddress;
    }
}